<template>
<NavBar  :color="'#fff'"  top='75rpx'>
  <view class="invite-page">
	 
    <!-- 背景图片 -->
    <image class="background-image" :src="invitePosterUrl" mode="aspectFill" />
    
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 标题文字区域 -->
      <view class="title-section">
        <image class="title-image-1" src="/static/chaogao.png" mode="aspectFit" />
        <image class="title-image-2" src="/static/xuehao.png" mode="aspectFit" />
      </view>
      
      <!-- 分享横幅 -->
      <view class="share-banner">
       分享一个学法减分考试神器给你
      </view>
      
     
    </view>
    
    <!-- 用户信息卡片 -->
    <view class="user-card">
		  <view class="user-avatar">
		     <image class="avatar-image" :src="userAvatarUrl" mode="aspectFit" />
		   </view>
		   <view class="user-info">
		     <text class="username">{{ userNickname }}</text>
		     <view class="user-id">
				 <view class="user-text">ID: {{ userId }}</view>
			 </view>
		   </view>
		   <view class="qr-placeholder">
		        <!-- 使用uqrcode-uni组件 -->
		        <image v-if="!qrCodeData" class="erweima" src="/static/uni.png" mode="scaleToFill" @click="testQRCode"></image>
		        <uqrcode-uni
		          v-else
		          ref="qrcode"
		          :value="qrCodeData"
		          :size="180"
		          :margin="0"
		          backgroundColor="#ffffff"
		          foregroundColor="#000000"
		          class="qr-code-component"
		          @complete="onQRCodeComplete"
		          @click="onQRCodeClick"
		        ></uqrcode-uni>
		   </view>
    </view>
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getAppConfig } from '../../utils/config.js'
import { getCurrentUser } from '../../utils/user.js'
// 响应式数据
const invitePosterUrl = ref('') // 邀请海报URL
const userAvatarUrl = ref('/static/profile/avatar.jpg') // 用户头像
const userNickname = ref('') // 用户昵称
const userId = ref('') // 用户ID
const qrCodeData = ref('') // 二维码数据
const qrcode = ref(null) // 二维码组件引用

// 处理头像URL，添加时间戳防止缓存
const processAvatarUrl = (userData) => {
  let avatarUrl = userData.avatar || '/static/profile/avatar.jpg'

  // 特殊处理默认头像
  if(userData.avatar && userData.avatar == "https://devoss.igmdns.com/avatar/avatar.jpg"){
    avatarUrl = '/static/profile/avatar.jpg'
  } else if (userData.avatar && userData.avatar.startsWith('http')) {
    // 对于网络图片，添加时间戳防止缓存
    const timestamp = Date.now()
    avatarUrl = userData.avatar.includes('?')
      ? `${userData.avatar}&t=${timestamp}`
      : `${userData.avatar}?t=${timestamp}`
  }

  return avatarUrl
}

// 获取用户数据并更新界面
const fetchUserData = () => {
  try {
    const userData = getCurrentUser()
    if (userData) {
      // 处理头像
      userAvatarUrl.value = processAvatarUrl(userData)

      // 设置昵称
      userNickname.value = userData.nickname || '用户'

      // 设置用户ID
      userId.value = userData.userid || ''

      console.log('用户数据更新:', {
        avatar: userAvatarUrl.value,
        nickname: userNickname.value,
        userid: userId.value
      })
    } else {
      console.log('未获取到用户数据')
    }
  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

// 生成二维码
const generateQRCode = async (userData) => {
  try {
    const appConfig = await getAppConfig()
    const inviteUrl = appConfig?.invite_config?.invite_url
    const userid = userData?.userid

    if (inviteUrl && userid) {
      // 拼接邀请链接
      const inviteLink = `${inviteUrl}?inviterId=${userid}`
      console.log('邀请链接:', inviteLink)

      // 设置二维码数据，组件会自动生成
      qrCodeData.value = inviteLink

      console.log('二维码数据设置完成:', inviteLink)
    } else {
      console.log('缺少邀请链接或用户ID，无法生成二维码')
      // 设置默认数据
      qrCodeData.value = 'https://www.example.com'
    }
  } catch (error) {
    console.error('生成二维码失败:', error)
    // 设置默认数据
    qrCodeData.value = 'https://www.example.com'
  }
}

// 二维码生成完成回调
const onQRCodeComplete = (result) => {
  console.log('二维码生成完成:', result)
  if (result.success) {
    console.log('二维码生成成功')
  } else {
    console.error('二维码生成失败:', result.error)
  }
}

// 二维码点击事件
const onQRCodeClick = () => {
  console.log('二维码被点击')
  uni.showActionSheet({
    itemList: ['保存到相册', '分享给朋友'],
    success: (res) => {
      if (res.tapIndex === 0) {
        saveToAlbum()
      } else if (res.tapIndex === 1) {
        shareToFriends()
      }
    }
  })
}

// 测试二维码生成
const testQRCode = () => {
  console.log('测试二维码生成')
  qrCodeData.value = 'https://www.example.com/test'

  // 延迟一下，让组件有时间渲染
  setTimeout(() => {
    if (qrcode.value) {
      qrcode.value.make()
    }
  }, 100)

  uni.showToast({
    title: '生成二维码',
    icon: 'none'
  })
}

// 获取公共配置中的邀请海报图片
const fetchInvitePoster = async () => {
  try {
    const appConfig = await getAppConfig()
    if (appConfig?.invite_config?.invite_poster_url) {
      invitePosterUrl.value = appConfig.invite_config.invite_poster_url
      console.log('邀请海报图片更新:', invitePosterUrl.value)
    }
  } catch (error) {
    console.error('获取邀请海报图片失败:', error)
    // 如果获取失败，使用默认图片
    invitePosterUrl.value = ''
  }
}

// 保存到相册
const saveToAlbum = () => {
  if (qrcode.value) {
    qrcode.value.save({
      success: () => {
        console.log('二维码保存成功')
      },
      fail: (err) => {
        console.error('二维码保存失败:', err)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  } else {
    uni.showToast({
      title: '二维码未生成',
      icon: 'none'
    })
  }
}

// 分享功能
const shareToFriends = () => {
  uni.showToast({
    title: '分享成功',
    icon: 'success'
  })
}

// 页面加载时获取配置
onMounted(async () => {
  // 获取用户数据
  fetchUserData()

  // 获取邀请海报
  await fetchInvitePoster()

  // 生成二维码
  const userData = getCurrentUser()
  if (userData) {
    await generateQRCode(userData)
  }
})
</script>

<style lang="scss" scoped>
.invite-page {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  position: relative;
  z-index: 10;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.time {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.back-icon {
  width: 24rpx;
  height: 24rpx;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.signal-icon, .wifi-icon, .battery-icon {
  width: 20rpx;
  height: 20rpx;
}

.save-button {
  position: absolute;
  top: 80rpx;
  right: 30rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  z-index: 10;
}

.save-text {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
}

.main-content {
  padding: 0 40rpx;
  text-align: center;
  position: relative;
  z-index: 5;
}

.title-section {
  margin-top: 260rpx;
}

.title-image-1 {
  display: block;
  width: 500rpx;
  height: 100rpx;
  margin: 0 auto 0;
}

.title-image-2 {
  display: block;
  width: 100%;
  max-width: 648rpx;
  height: 100rpx;
  margin: 0 auto 0;
}
.share-banner {
  background: linear-gradient(135deg, #8B5CF6, #A855F7);
  border-radius: 30rpx;
  padding:0 30rpx;
  margin: 0 auto;
  max-width: 500rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 58rpx;
  color: white;
  font-size: 28rpx;
  font-weight: 600;
  text-align: center;
}



.center-graphic {
  position: relative;
  margin: 80rpx 0;
  height: 450rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-graphic {
  width: 100%;
  max-width: 600rpx;
  height: auto;
  max-height: 400rpx;
}

.user-card {
  position: absolute;
  bottom: 96rpx;
  left: 30rpx;
  right: 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  height: 232rpx;
  background-color: #fff;
  box-sizing: border-box;
background: rgba(255, 255, 255, 0.6); /* 半透明白色背景 */

}
// .user-card-img{
// 	position: absolute;
// 	left: 0;
// 	top: 0;
// 	width: 690rpx;
// 	height: 320rpx;
// 	z-index: 1;
// }
.user-avatar {
  width: 112rpx;
  height: 112rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.user-card-info{
	position: absolute;
	left: 0;
	top: 0;
	z-index: 5;
}
.avatar-image {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
  width: 105rpx;
  height: 105rpx;
  border-radius: 50%;
}

.user-info {
  flex: 1;
  min-width: 0; /* 允许flex项目收缩 */
  padding-right: 20rpx; /* 给右侧二维码留出空间 */
}

.username {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #20257B;
  margin-bottom: 8rpx;
  max-width: 350rpx;
  word-wrap: break-word;
  word-break: break-all;
  line-height: 1.4;
}

.user-id {
  color: #666;
  width: 184rpx;
  height: 30rpx;
  border-radius: 30rpx;
  background-color: #7F94DC;
  padding: 3rpx;
  line-height: 30rpx;
}
.user-text{
  background-color: #fff;	
  width: 100%;
  height: 100%;
    border-radius: 30rpx;
	color: #7F94DC;
	font-size: 20rpx;
	padding-left: 10rpx;
	box-sizing: border-box;
}

.qr-placeholder {
  width: 182rpx;
  height: 182rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border:2rpx solid #707070;
  background: #B2B2B2;
  border-radius: 26rpx 26rpx 26rpx 26rpx;
}
.erweima{
	width: 180rpx;
	height: 180rpx;
	border-radius: 26rpx 26rpx 26rpx 26rpx;
}

.qr-code-component {
	border-radius: 26rpx;
	overflow: hidden;
	width: 180rpx;
	height: 180rpx;
}
.qr-text {
  font-size: 20rpx;
  color: #999;
  text-align: center;
}


</style>
